<template>
    <div class="websocket-container">
        <!-- 连接状态显示 -->
         <span>{{ connectionError }}</span>
        <div class="status" :class="status">
            {{ connectionStatusText }} | {{ channelId }}
        </div>

        <!-- 连接控制 -->
        <div class="controls">
            <button @click="connect" :disabled="isOpen">
                {{ isOpen ? '已连接' : connectionStatusText }}
            </button>
            <button @click="reconnect" :disabled="isOpen">
                {{ isOpen ? '已连接' : '重新连接' }}
            </button>
            <button @click="closeConnection" :disabled="!isOpen">
                断开连接
            </button>
        </div>

        <!-- 消息发送区 -->
        <div class="message-box">
            目标频道ID:
            <input v-model="toChannelId" placeholder="输入目标频道ID..." /><br/>
            <input v-model="messageInput" @keyup.enter="sendMessage" placeholder="输入消息..." :disabled="!isOpen" />
            <button @click="sendMessage" :disabled="!isOpen || !messageInput.trim()">
                发送
            </button>
        </div>

        <!-- 消息历史记录 -->
        <div class="message-history">
            <div v-for="(msg, index) in messageHistory" :key="index" class="message">
                <span class="timestamp">{{ msg.timestamp }}</span>
                <span class="content">{{ msg.content }}</span>
            </div>
        </div>
    </div>
</template>

<script setup lang="ts">
import { ref, computed, watch } from 'vue'
import { useWebSocket } from '@vueuse/core'

const connectionError = ref('') // 存储错误信息

// WebSocket 配置
const wsUrl = ref('ws://127.0.0.1:8081/ws?token=123')
const { status, data, send, open, close} = useWebSocket(wsUrl, {
    // 自动重连配置
    autoReconnect: {
        retries: 1,
        delay: 3000,
        onFailed() {
            console.error('WebSocket 连接失败')
        }
    },
    // 心跳检测
    heartbeat: false,
    // heartbeat: {
    //     interval: 30000,
    //     message: JSON.stringify({ type: 'ping', timestamp: new Date().toISOString() })
    // },
    // 连接成功回调
    onConnected(ws) {
        console.log('WebSocket 已连接:', ws)
    },
    // 连接断开回调
    onDisconnected(ws, event) {
        console.log('WebSocket 断开:', {
            code: event.code,
            reason: event.reason,
            wasClean: event.wasClean
        });
        
        // 根据关闭代码判断断开原因
        if(event.code === 1008) {
            // 1008 - Policy Violation: 策略违规。
            // 表示终端因收到的消息违反其策略而终止连接。这通常用于认证失败或隐藏特定细节。
            connectionError.value = event.reason
            close();
        }else if (event.code === 1000) {
            close();
        } else {
            connectionError.value = `连接异常断开 (代码: ${event.code})`
        }
    },
    // 错误处理
    onError(ws, event) {
        console.error('WebSocket 错误:', event)
    },
})

// 本地状态
const messageInput = ref('')
const messageHistory = ref<Array<{ content: string; timestamp: string }>>([])

// 计算属性
const isOpen = computed(() => status.value === 'OPEN')
const connectionStatusText = computed(() => {
    const statusMap: Record<string, string> = {
        CONNECTING: '连接中...',
        OPEN: '已连接',
        CLOSED: '已断开',
        ERROR: '连接错误'
    }
    return statusMap[status.value] || `未知状态 (${status.value})`
})

let channelId = ref('')
const toChannelId = ref('')
// 监听收到的消息
watch(data, (newData) => {
    if (newData) {
        const parsed = JSON.parse(newData)
        console.log('收到消息:', parsed["payload"])
        const payload = parsed["payload"]
        const type = parsed["type"]
        if('status' === type) {
            const message = payload["message"];
            if(message === 'connected') {
                channelId.value = payload["channelId"];
                console.log('连接成功, 频道ID:', channelId.value);
            } else if(message === 'disconnected') {
                console.log('连接已断开');
            } else {
                console.log('未知状态:', message);
            }
        }
        messageHistory.value.push({
            content: parsed,
            timestamp: new Date().toLocaleTimeString()
        })
        
    }
})

// 发送消息
const sendMessage = () => {
    if (messageInput.value.trim() && isOpen.value) {
        const message = {
            version: '1.0',
            type: 'message', // 消息类型 message/command/status
            payload: {
                content: messageInput.value.trim(),
                toChannelId: toChannelId.value.trim()
            },
            timestamp: new Date().toISOString()
        }
        send(JSON.stringify(message))
        messageInput.value = ''
    }
}

// 手动连接
const connect = () => {
    if (!isOpen.value) {
        open()
    }
}

// 手动重新连接
const reconnect = () => {
    if (!isOpen.value) {
        open()
    }
}

// 手动断开连接
const closeConnection = () => {
    if (isOpen.value) {
        channelId.value = ''
        close()
    }
}
</script>

<style lang="scss" scoped>
.websocket-container {
    max-width: 600px;
    margin: 0 auto;
    padding: 20px;
    font-family: Arial, sans-serif;

    .status {
        padding: 8px;
        border-radius: 4px;
        margin-bottom: 16px;
        text-align: center;
        font-weight: bold;

        &.OPEN {
            background-color: #e6f7e6;
            color: #2e7d32;
        }

        &.CONNECTING {
            background-color: #fff8e1;
            color: #ff8f00;
        }

        &.CLOSED,
        &.ERROR {
            background-color: #ffebee;
            color: #c62828;
        }
    }

    .controls {
        display: flex;
        gap: 10px;
        margin-bottom: 16px;

        button {
            padding: 8px 16px;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            transition: background-color 0.3s;

            &:disabled {
                opacity: 0.6;
                cursor: not-allowed;
            }

            &:not(:disabled):hover {
                opacity: 0.9;
            }
        }
    }

    .message-box {
        display: flex;
        gap: 10px;
        margin-bottom: 20px;

        input {
            flex: 1;
            padding: 8px;
            border: 1px solid #ddd;
            border-radius: 4px;
        }

        button {
            padding: 8px 16px;
            background-color: #1976d2;
            color: white;
            border: none;
            border-radius: 4px;
            cursor: pointer;

            &:disabled {
                background-color: #90caf9;
                cursor: not-allowed;
            }
        }
    }

    .message-history {
        border: 1px solid #eee;
        border-radius: 4px;
        max-height: 400px;
        overflow-y: auto;

        .message {
            padding: 10px;
            border-bottom: 1px solid #eee;

            &:last-child {
                border-bottom: none;
            }

            .timestamp {
                color: #666;
                font-size: 0.8em;
                margin-right: 10px;
            }
        }
    }
}
</style>